import os
import re

import matplotlib.pyplot as plt
import pandas as pd

buildPoints = []
lastMappID = 0


def getBuildPoints(mapID, otherMap='无'):
    global lastMappID
    global buildPoints
    if buildPoints and lastMappID == mapID: return buildPoints
    lastMappID = mapID
    if mapID == 1:
        excel_file = '..\\data\\4-拙政园数据坐标.xlsx'
    elif mapID == 2:
        excel_file = '..\\data\\4-留园数据坐标.xlsx'
    elif mapID == 3:
        excel_file = '..\\data\\4-寄畅园数据坐标.xlsx'
    elif mapID == 4:
        excel_file = '..\\data\\4-瞻园数据坐标.xlsx'
    elif mapID == 5:
        excel_file = '..\\data\\4-豫园数据坐标.xlsx'
    elif mapID == 6:
        excel_file = '..\\data\\4-秋霞圃数据坐标.xlsx'
    elif mapID == 7:
        excel_file = '..\\data\\4-沈园数据坐标.xlsx'
    elif mapID == 8:
        excel_file = '..\\data\\4-怡园数据坐标.xlsx'
    elif mapID == 9:
        excel_file = '..\\data\\4-耦园数据坐标.xlsx'
    elif mapID == 10:
        excel_file = '..\\data\\4-绮园数据坐标.xlsx'
    else:
        excel_file = os.path.join('..\\data\\', otherMap)
    # 读取Excel的“道路”工作表
    df = pd.read_excel(excel_file, sheet_name='半开放建筑')

    # 提取第一列数据（区分线段的坐标）
    raw_data = df.iloc[:, 0].dropna().astype(str)
    segments = []  # 存储所有线段
    current_segment = []  # 当前线段点列表
    for item in raw_data:
        if item.startswith('            {0;'):
            # 新线段开始：保存当前线段（如果有），并重置
            if current_segment:
                segments.append(current_segment)
            current_segment = []
            segment_id = int(re.findall(r'\d+', item)[0])  # 提取线段ID
        else:

            # 解析坐标点：格式为 "b.{x,y,z}"
            if(mapID <= 10):
                match = re.match(r'(\d+)\. \{([-\d.]+), ([-\d.]+), ([-\d.]+)\}', item)
                if match:
                    b = int(match.group(1))
                    x = float(match.group(2))
                    y = float(match.group(3))
                    current_segment.append((x, y))
            else:
                match = re.match(r'\(([-\d.]+), ([-\d.]+), ([-\d.]+)\)', item)
                if match:
                    x = float(match.group(1))
                    y = float(match.group(2))
                    current_segment.append((x, y))

    if current_segment:
        segments.append(current_segment)
    buildPoints = segments
    return segments


def getBuildCenterPoints(mapID):
    average = []
    points = getBuildPoints(mapID)
    for line in points:
        df = pd.DataFrame(line, columns=['x', 'y'])
        average_x = df['x'].mean()
        average_y = df['y'].mean()
        if ((average_x * average_x + average_y * average_y) - (line[0][0] * line[0][0] + line[0][1] * line[0][1])) < (
                10000 ^ 2):
            average.append((average_x, average_y))
    return average
